package com.huluobo.a2109kotlinshopping.home

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.huluobo.a2109kotlinshopping.R
import com.huluobo.a2109kotlinshopping.base.BaseMVVMFragment
import com.huluobo.a2109kotlinshopping.databinding.FragmentHomeBinding
import com.huluobo.a2109kotlinshopping.detail.DetailActivity
import com.huluobo.a2109kotlinshopping.net.Const
import com.huluobo.a2109kotlinshopping.utils.ImageUtils
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader

class HomeFragment : BaseMVVMFragment<FragmentHomeBinding>() {
    private lateinit var viewModel: HomeViewModel

    //适配器
    private lateinit var goodsListAdapter: HomeGoodsListAdapter

    //数据源
    private val goodsList = mutableListOf<HomeGoodsBean>()

    //banner的数据源
    private val bannerUrls = mutableListOf<String>()

    //上拉加载更多需要更新的currentPage
    private var currentPage = 1

    //导航的adapter
    private lateinit var navAdapter: HomeNavAdapter

    //导航的数据源
    private val navList = mutableListOf<NavBean>()
    override fun getLayoutId(): Int = R.layout.fragment_home

    override fun initData() {
        viewModel = ViewModelProvider(requireActivity())[HomeViewModel::class.java]

        viewModel.getHomeGoodsList(0, currentPage, 10)
        viewModel.getHomeBanner()
        viewModel.getHomeNav()

        viewModel.homeGoodsListSuccess.observe(this) {
            if (it.code == 200) {
                //当currentPage等于1的时候,要么是初始化的状态,要么是下拉刷新的状态,需要重置list
                if (currentPage == 1) {
                    goodsList.clear()
                }
                //停止刷新和加载
                dataBinding.homeRefresh.finishRefresh()
                dataBinding.homeRefresh.finishLoadMore()
                goodsList.addAll(it.data)
                goodsListAdapter.notifyDataSetChanged()
            } else {
                ToastUtils.showLong("获取首页数据失败:${it.message}")
            }
        }

        viewModel.homeGoodsListFailed.observe(this) {
            Log.i("TagA", "获取首页list失败:$it")
        }

        viewModel.homeBannerSuccess.observe(this) {
            if (it.code == 200) {
                bannerUrls.clear()
                it.data.forEach {
                    bannerUrls.add(it.imagePath)
                }
                dataBinding.homeBanner.setImages(bannerUrls)
                dataBinding.homeBanner.start()
            } else {
                ToastUtils.showLong(it.message)
            }

        }

        viewModel.homeBannerFailed.observe(this) {
            Log.i("TagA", "获取首页banner失败:$it")
        }

        viewModel.homeNavSuccess.observe(this) {
            if (it.code == 200) {
                navList.clear()
                navList.addAll(it.data[0].data!!)
                navAdapter.notifyDataSetChanged()
            }
        }

        viewModel.homeNavFailed.observe(this) {
            Log.i("TagA", "获取首页nav失败:$it")
        }
    }

    override fun initView() {
        //初始化商品列表
        dataBinding.homeRv.layoutManager = GridLayoutManager(requireContext(), 2)

        goodsListAdapter = HomeGoodsListAdapter(goodsList)

        dataBinding.homeRv.adapter = goodsListAdapter

        //设置首页item的点击事件
        goodsListAdapter.setOnItemClickListener { adapter, view, position ->
            val intent = Intent(requireActivity(), DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, goodsList[position].id)
            startActivity(intent)
        }


        //初始化banner
        dataBinding.homeBanner.setBannerStyle(BannerConfig.NUM_INDICATOR)
        dataBinding.homeBanner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                if (context != null && imageView != null) {
//                    Glide.with(context).load(path).into(imageView)
                    ImageUtils.loadImage(context, path.toString(), imageView)
                }
            }
        })
        dataBinding.homeBanner.setDelayTime(2000)
        dataBinding.homeBanner.setIndicatorGravity(BannerConfig.CENTER)

        //初始化下拉刷新,上拉加载
        dataBinding.homeRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                //需要在刷新的同时判断一下当前刷新框架有没有在加载,如果在加载,停止加载
                if (refreshLayout.isLoading) {
                    refreshLayout.finishLoadMore()
                }
                //重置page,可以从新开始刷新
                currentPage = 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                //如果加载的时候正在刷新,则停止刷新
                if (refreshLayout.isRefreshing) {
                    refreshLayout.finishRefresh()
                }
                currentPage += 1
                viewModel.getHomeGoodsList(0, currentPage, 10)
            }
        })

        //初始化导航
        dataBinding.homeNavRv.layoutManager = GridLayoutManager(context, 5)
        navAdapter = HomeNavAdapter(navList)
        dataBinding.homeNavRv.adapter = navAdapter
    }
}